package com.jojo.intermediate.day7_string;

import java.util.HashMap;
import java.util.Map;

/**
 * 290、单词规律
 *
 * 给定一种规律 pattern和一个字符串s，判断 s是否遵循相同的规律。
 * 这里的遵循指完全匹配，例如，pattern里的每个字母和字符串s中的每个非空单词之间存在着双向连接的对应规律。
 *
 * 示例1:
 * 输入: pattern = "abba", s = "dog cat cat dog"
 * 输出: true
 *
 * 示例 2:
 * 输入: pattern = "abba", s = "dog cat cat fish"
 * 输出: false
 *
 * 示例 3:
 * 输入: pattern = "aaaa", s = "dog cat cat dog"
 * 输出: false
 */
public class WordRule {

    /** myCode Hash表 */
    public boolean wordPattern(String pattern, String s) {
        String[] ss = s.split(" ");
        char[] chars = pattern.toCharArray();
        if (ss.length != chars.length){
            return false;
        }
        Map<Character,String> map = new HashMap<>();
        Map<String,Character> strMap = new HashMap<>();
        for (int i = 0;i < chars.length;i++){
            if (map.containsKey(chars[i])){
               if (!map.get(chars[i]).equals(ss[i])){
                   return false;
               }
            }else{
                map.put(chars[i],ss[i]);
            }
            if (strMap.containsKey(ss[i])){
                if (!strMap.get(ss[i]).equals(chars[i])){
                    return false;
                }
            }else{
                strMap.put(ss[i],chars[i]);
            }
        }
        return true;
    }

    /** pe.Hash表 */
    public boolean wordPattern2(String pattern, String str) {
        Map<String, Character> str2ch = new HashMap<>();
        Map<Character, String> ch2str = new HashMap<>();
        int m = str.length();
        int i = 0;
        for (int p = 0; p < pattern.length(); ++p) {
            char ch = pattern.charAt(p);
            if (i >= m) {
                return false;
            }
            int j = i;
            while (j < m && str.charAt(j) != ' ') {
                j++;
            }
            String tmp = str.substring(i, j);
            if (str2ch.containsKey(tmp) && str2ch.get(tmp) != ch) {
                return false;
            }
            if (ch2str.containsKey(ch) && !tmp.equals(ch2str.get(ch))) {
                return false;
            }
            str2ch.put(tmp, ch);
            ch2str.put(ch, tmp);
            i = j + 1;
        }
        return i >= m;
    }

    public static void main(String[] args) {
        WordRule wordRule = new WordRule();
        String pattern = "abba";
        String s1 = "dog cat cat dog";
        String s2 = "dog cat cat fish";
        String s3 = "dog dog dog dog";
        boolean b = wordRule.wordPattern(pattern, s3);
        System.out.println(b);
    }
}
